<?php

namespace addons\shopro\job;

use addons\shopro\library\traits\ActivityCache;
use addons\shopro\library\traits\Groupon;
use addons\shopro\library\traits\StockSale;
use addons\shopro\model\ActivityGoodsSkuPrice;
use addons\shopro\model\Goods;
use addons\shopro\model\GoodsComment;
use addons\shopro\model\GoodsSkuPrice;
use addons\shopro\model\Order;
use addons\shopro\model\OrderAction;
use addons\shopro\model\OrderItem;
use addons\shopro\model\ScoreGoodsSkuPrice;
use addons\shopro\model\User;
use think\Db;
use think\queue\Job;

/**
 * 订单支付完成
 */
class OrderPayed extends BaseJob
{
    use StockSale, ActivityCache, Groupon;

    /**
     * 订单支付完成
     */
    public function payed(Job $job, $data)
    {
        try {
            $order = $data['order'];
            $user = $data['user'];
            log_print(000000);
            $order = Order::with('item')->where('id', $order['id'])->find();

            // 数据库删订单的问题常见，这里被删的订单直接把队列移除
            if ($order) {
                \think\Db::transaction(function () use ($order, $user, $data) {
                    // 订单减库存
                    $this->realForwardStockSale($order);

                    // 判断，如果是拼团 真实加入团
                    if (strpos($order['activity_type'], 'groupon') !== false) {
                        $this->joinGroupon($order, $user);
                    }

                    // 处理发票审核
                    if ($order->invoice_status == 1) {
                        $invoice = \addons\shopro\model\OrderInvoice::get(['order_id' => $order->id]);
                        if ($invoice) {
                            $invoice->status = 0;
                            $invoice->save();
                        }
                    }
                    //会员专区
                    $this->vip($order);

                    // 触发订单支付完成事件, 如果这个订单刚好完成拼团，并且是自动发货订单，则这个订单的自动发货事件会比订单支付之后事件早
                    $data = ['order' => $order];
                    \think\Hook::listen('order_payed_after', $data);

                    // 检测有没有自动发货的商品，有就自动发货
                    $order->checkDispatchAndSend($order, ['user' => $user]);
                });
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            $error = json_encode([
                'a' => $e->getLine(),
                'b' => $e->getFile(),
                'c' => $e->getTrace(),
                'd' => $e->getMessage()
            ], JSON_UNESCAPED_UNICODE);


            \think\Log::error('queue-' . get_class() . '-payed' . '：执行失败，错误信息：' . $error);
        }
    }

    public function vip($order){
//        log_print(1111);
        $items = OrderItem::where('order_id', $order['id'])->select();
        foreach ($items as $key => $orderItem) {
//            log_print($orderItem);
            if($orderItem['goods_type']=='vip'){

                //查询商品
//                log_print(2222);
                $goodsItem = Goods::where('id', $orderItem->goods_id)->find();
//                log_print($goodsItem['freeze_gold']);
                $userItem = User::get(['id' => $orderItem['user_id']]);
//                log_print($orderItem['pay_price']);
                //判断是否复购
                $orderCount=Order::where(['user_id'=>$orderItem['user_id']])->count();
                if ($orderCount>1){
                    //订单数量大于1表示复购,只添加冻结和固定
                    $orderItem['pay_price']=0;//消费金额为0
                }
                $userdata = [
                    'total_consume'=>$userItem['total_consume'] + $orderItem['pay_price'],
                    'freeze_gold'=>$userItem['freeze_gold']+$goodsItem['freeze_gold'],
                    'fixed_gold' => $userItem['fixed_gold'] + $goodsItem['thaw_gold']
                ];
                User::thaw_gold('+'.$goodsItem['freeze_gold'], $orderItem['user_id'], 'freeze', $order['id'], '',[
                    'order_id' => $order['id'],
                    'goods_id' => $orderItem['goods_id'],
                ]);
                User::score('+'.$goodsItem['give_vouchers'], $orderItem['user_id'], 'score_refund', $order['id'], '购买返消费劵',[
                    'order_id' => $order['id'],
                    'goods_id' => $orderItem['goods_id'],
                ]);
//                log_print(3333);
                if ($orderCount==1){
                    //第一个订单添加消费额及团队消费额
                    \app\common\model\User::consume($order['total_amount'],$orderItem['user_id']);
                }

//                log_print(4444);
                //增加用户赠送黄金，赠送消费券，冻结黄金券，每天释放黄金券
                $userItem->save($userdata);
            }
        }
        //查询上级信息
        $uid = $order['user_id'];
        $user = User::where(array('id'=>$uid))->find();
        if(!empty($user['parent_user_id'])){
            User::where(array('id'=>$user['parent_user_id']))->setInc('fg_child_order');
        }
    }
}
